//all data use Little Endian
//data frame: 0xEA device_id data_length data sum 0x1D
//id frame: 0xEE device_id 0x1D
//debug frame: 0xEC data_length_str data_hex_str 0x1D
const uint8_t dataServer_frame_end = 0x1D;

//must define variables by other files 
extern uint8_t dataServer_deviced_id;
extern uint8_t dataServer_length;
extern uint8_t* dataServer_data;
//custom function
void (*dataServer_custom_function)(HardwareSerial &ser) = NULL;

void dataServer_parse_query(HardwareSerial &ser) {
  uint16_t read_count = 0;
  const uint16_t read_max = 1024;
  int tmp;
  while (ser.available() > 0 && read_count++ < read_max) {
    switch(ser.read()) {
      case '0'://output device id
        ser.write(0xEE);//frame head
        ser.write(dataServer_deviced_id);
        ser.write(dataServer_frame_end);
        break;
      case '1'://output data
        dataServer_output_data(ser);
        break;
      case '2'://output device id by hex
        ser.print(0xEC, HEX);//frame head
        ser.print(" len=");
        ser.print(1);
        ser.print(" ");
        ser.print(dataServer_deviced_id, HEX);
        ser.print(" ");
        ser.println(dataServer_frame_end, HEX);
        break;
      case '3'://output data by hex
        ser.print(0xEC, HEX);//frame head
        ser.print(" len=");
        ser.print(dataServer_length);
        ser.print(" ");
        for(uint8_t i = 0; i < dataServer_length; i++) {
          ser.print(dataServer_data[i], HEX);
          ser.print(" ");
        }
        ser.println(dataServer_frame_end, HEX);
        break;
      case '4'://set deviced id (use next byte)
        tmp = ser.parseInt();
        if(tmp >= 0) {
          dataServer_deviced_id = tmp;
          ser.print("OK. Set to 0x");
          ser.println(tmp, HEX);
        }
        else
          ser.println("Set id fail.");
        break;
      case '5':
        if(dataServer_custom_function)
          dataServer_custom_function(ser);//call uesr custom function
        break;
    }
  }
}

void dataServer_output_data(HardwareSerial &ser) {
  ser.write(0xEA);//frame head
  ser.write(dataServer_deviced_id);
  ser.write(dataServer_length);
  ser.write(dataServer_data, dataServer_length);
  //calc sum
  uint8_t sum = 0;
  for(uint8_t i = 0; i < dataServer_length; i++)
    sum += dataServer_data[i];
  ser.write(sum);
  ser.write(dataServer_frame_end);
}

